const router = require('koa-router')()
const path = require('path')
const fs = require('fs');
const moment = require('moment');
const jwt = require("jsonwebtoken");
const { formidable } = require('formidable');
const myKey = "2114i";
let expir = 60 * 60 * 3;//3小时(token过期时间)
//个人模块
//1.用户登录 
//2.用户注册
//3.修改个人信息

//1.登录
router.post('/login', async (ctx, next) => {
    let usernumber = ctx.request.body.userNumber;
    let pwd = ctx.request.body.password;
    let sql = `select * from users where user_number = '${usernumber}' `;
    let results = await ctx.db.EXCUTE(sql, []);
    if (results.length) {
        let sql = `select * from users where user_number = '${usernumber}' and user_pwd = '${pwd}' `;
        let user = await ctx.db.EXCUTE(sql, []);
        if (user.length) {
            let userName = user[0].user_name;
            let roleId = user[0].user_roleid;
            let sql2 = `select * from roles where role_id = ${roleId} `;
            let role = await ctx.db.EXCUTE(sql2, []);
            let roleName = role[0].role_desc;
            let date = moment().format('YYYY-MM-DD HH:mm:ss');
            let sql3 = `insert into logindiary (userName, userRole, userDate) values('${userName}','${roleName}','${date}')`
            await ctx.db.EXCUTE(sql3, []);
            let token = jwt.sign({ userNumber: usernumber, pwd: pwd }, myKey, { expiresIn: expir })
            ctx.body = {
                "status": 200,
                "msg": '登录成功',
                "token": token,
                "data": user[0]
            }
        } else {
            ctx.body = {
                "status": 403,
                "msg": '密码错误'
            }
        }
    } else {
        ctx.body = {
            "status": 403,
            "msg": '用户不存在'
        }
    }
})

//3.修改信息
router.put('/userInfo', async (ctx, next) => {
    let id = ctx.request.body.id;
    let userName = ctx.request.body.userName;
    let number = ctx.request.body.userNumber;
    let sql = `update users set user_name = '${userName}', user_number = '${number}' WHERE user_id = ${id}`;
    await ctx.db.EXCUTE(sql, []);
    ctx.body = {
        "status": 200,
        "msg": '修改成功'
    }
})

//用户修改个人密码
router.put('/userPwd', async (ctx, next) => {
    let id = ctx.request.body.id;
    let formalPwd = ctx.request.body.formalPwd;
    let normalPwd = ctx.request.body.normalPwd;
    //核验旧密码
    let sql = `select user_pwd from users where user_id = '${id}' `;
    let results = await ctx.db.EXCUTE(sql, []);
    let correctPwd = results[0].user_pwd;
    if (formalPwd == correctPwd) {
        let sql = `update users set user_pwd = '${normalPwd}' WHERE user_id = ${id}`;
        await ctx.db.EXCUTE(sql, []);
        ctx.body = {
            "status": 200,
            "msg": '修改密码成功'
        }
    } else {
        ctx.body = {
            "status": 401,
            "msg": '原密码输入错误'
        }
    }
})

//4.上传头像
router.post('/uploadavatar', async (ctx, next) => {
    let form = formidable({
        uploadDir: path.resolve(__dirname, '../public/useravatars'),
        //是否保留扩展名
        keepExtensions: true,
        //将文件作为数组出现
        multiples: true
    })
    form.parse(ctx.req, async (err, fields, files) => {
        if (err) {
            console.log(err)
        } else {
            let id = JSON.parse(fields.id);
            let src;
            if (files.image) {
                src = 'http://localhost:3000/useravatars/' + files.image[0].newFilename
            } else {
                src = JSON.parse(fields.data).src;
            }
            let sql = `update users set user_avatar = '${src}' WHERE user_id = ${id}`
            await ctx.db.EXCUTE(sql, [])
        }
    })
    ctx.body = {
        "status": 200,
        "msg": '编辑成功',
    }
})

//获取个人信息
router.get('/userInfo', async (ctx, next) => {
    let id = ctx.request.query.userId;
    let sql = `select * from users where user_id = ${id}`;
    let results = await ctx.db.EXCUTE(sql, []);
    let obj = {
        results: results,
        status: 200
    }
    ctx.body = JSON.stringify(obj);
})


//获取图片
// router.get("/:id", async (ctx, next) => {
//     let urlObj = new URL(ctx.req.url, "http://localhost:3000/")
//     let name = urlObj.pathname.split("/");
//     let filePath = __dirname + '/upload/' + name[1];
//     let fileContent = fs.readFileSync(filePath);
//     ctx.res.writeHead(200, { "Content-Type": "image/png" });
//     ctx.res.end(fileContent);
// })

router.get('/', async (ctx, next) => {
    await ctx.render('index', {
        title: 'Hello Koa 2!'
    })
})

router.get('/string', async (ctx, next) => {
    ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
    ctx.body = {
        title: 'koa2 json'
    }
})
module.exports = router
